package fm.demo.smart.collection.speaker;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.Base64Utils;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;

@SpringBootApplication
public class Application {

    private Logger logger = LoggerFactory.getLogger(Application.class);

    @Bean
    public CommandLineRunner commandLineRunner(ObjectMapper objectMapper, RestTemplateBuilder restTemplateBuilder) {
        return args -> {
            // 目标地址
            final String targetURL = "http://bj.echase.cn:8073/cloudspeaker/api/notify";
            // 机构ID
            final String orgNum = "1041";

            RestTemplate restTemplate = restTemplateBuilder.build();
//            RestTemplate restTemplate = new RestTemplate();
            TTSEntity ttsEntity = new TTSEntity();
            ttsEntity.setOrgNum(orgNum);
            ttsEntity.setBcType("3");
            ttsEntity.setMsgId(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "0001");
            ttsEntity.setTimestamp(System.currentTimeMillis() + "");
            ttsEntity.setTransNo("0");
            ttsEntity.setVoiceData(Base64Utils.encodeToString("您有一个新的订单，请查收".getBytes(StandardCharsets.UTF_8)));
            ttsEntity.setVoiceType("");
            Device device = new Device();
            device.setDeviceId("010132018XC6201896");
            device.setDeviceIndex("1");
            ttsEntity.setDeviceList(Collections.singletonList(device));
//            objectMapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
            String s = ttsEntity.toSignTree(objectMapper);
            PrivateKey priKey = RSAUtils.getPriKey();
            String sign = RSAUtils.getSign(s, priKey);
            ttsEntity.setSign(sign);


//            System.out.println(RSAUtils.verifySign(sign, s));

            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<TTSEntity> ttsEntityHttpEntity = new HttpEntity<>(ttsEntity, httpHeaders);
            restTemplate.setInterceptors(Collections.singletonList(new ClientHttpRequestInterceptor() {
                @Override
                public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
                    logger.info("===========================request begin================================================");
                    logger.info("URI         : {}", request.getURI());
                    logger.info("Method      : {}", request.getMethod());
                    logger.info("Headers     : {}", request.getHeaders());
                    logger.info("Request body: {}", new String(body, "UTF-8"));
                    logger.info("==========================request end================================================");
                    ClientHttpResponse response = execution.execute(request, body);
//                    logger.info("============================response begin==========================================");
//                    logger.info("Status code  : {}", response.getStatusCode());
//                    logger.info("Status text  : {}", response.getStatusText());
//                    logger.info("Headers      : {}", response.getHeaders());
//                    logger.info("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()));
//                    logger.info("=======================response end=================================================");
                    return response;
                }
            }));
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(URI.create(targetURL), ttsEntityHttpEntity, String.class);
            logger.info("============================response begin==========================================");
            logger.info("Status code  : {}", stringResponseEntity.getStatusCode());
            logger.info("Headers      : {}", stringResponseEntity.getHeaders());
            String r = stringResponseEntity.getBody();
            logger.info("Response body: {}", r);
            logger.info("=======================response end=================================================");
            System.exit(0);
        };
    }


    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}
